<?php

/**
 * 扩展array
 */
if (! function_exists ( 'extend' )) {
  function extend($config, $default) {
    foreach ( $default as $key => $val ) {
      if (! isset ( $config [$key] )) {
        $config [$key] = $val;
      } else if (is_array ( $config [$key] )) {
        $config [$key] = extend ( $config [$key], $val );
      }
    }
    
    return $config;
  }
}

/**
 * ajax_arr
 */
if (! function_exists ( 'ajax_arr' )) {
  function ajax_arr($info, $status = FALSE, $ret = array()) {
    $ret ['info'] = $info;
    $ret ['status'] = $status;
    return $ret;
  }
}

/**
 * 判断str是否用户名
 */
if (! function_exists ( 'is_username' )) {
  function is_username($str) {
    $s = trim ( $str );
    if (strlen ( $s ) < 3 || strlen ( $s ) > 20) {
      return FALSE;
    } else {
      return TRUE;
    }
  }
}

/**
 * 判断str是否网站
 */
if (! function_exists ( 'is_url' )) {
  function is_url($str) {
    return filter_var ( $str, FILTER_VALIDATE_URL );
  }
}

/**
 * 判断str是否email
 */
if (! function_exists ( 'is_email' )) {
  function is_email($str) {
    return filter_var ( $str, FILTER_VALIDATE_EMAIL );
  }
}
if (! function_exists ( 'rmdirs' )) {
  function rmdirs($dir) {
    $d = dir ( $dir );
    while ( false !== ($child = $d->read ()) ) {
      if ($child != '.' && $child != '..') {
        if (is_dir ( $dir . '/' . $child ))
          rmdirs ( $dir . '/' . $child );
        else
          unlink ( $dir . '/' . $child );
      }
    }
    $d->close ();
    rmdir ( $dir );
  }
}
/**
 * 判断str是否phone
 */
if (! function_exists ( 'is_phone' )) {
  function is_phone($str) {
    $search = '/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8]))\d{8}$/';
    return preg_match ( $search, $str );
  }
}

if (! function_exists ( 'site_url' )) {
  function site_url($url = '') {
    $base_url = base_url ();
    return str_replace ( '\\', '', $base_url . $url );
  }
}

if (! function_exists ( 'base_url' )) {
  function base_url() {
    return C ( 'BASE_URL' );
  }
}

if (! function_exists ( 'delete_file' )) {
  function delete_file($filename) {
    if (file_exists ( $filename )) {
      unlink ( $filename );
    }
  }
}

if (! function_exists ( 'gameover' )) {
  function gameover($tips) {
    header ( 'Content-Type:text/html; charset=utf-8' );
    exit ( $tips );
  }
}

if (! function_exists ( 'site_url' )) {
  function site_url($url = '') {
    $base_url = C ( 'BASE_URL' );
    
    $ret = str_replace ( '\\', '', $base_url . $url );
    return str_replace ( './', '', $ret );
  }
}

if (! function_exists ( 'base_url' )) {
  function base_url() {
    return C ( 'BASE_URL' );
  }
}

if (! function_exists ( 'form_options' )) {
  function form_options($data, $selected_value = -1) {
    $html = '';
    foreach ( $data as $key => $val ) {
      $html .= "<option value='$key'>$val</option>";
    }
    
    if ($selected_value >= 0) {
      $html = str_replace ( "value='$selected_value'", "value='$selected_value' selected", $html );
    }
    return $html;
  }
}

if (! function_exists ( 'form_options_rows' )) {
  function form_options_rows($data, $id = 'id', $text = "name", $selected_value = 0, $dat = array()) {
    $html = '';
    foreach ( $data as $row ) {
      $value = $row [$id];
      $prefix = '';
      if (isset ( $row ['level'] )) {
        $prefix = $row ['level'] - 1 > 0 ? str_repeat ( '&nbsp;', $row ['level'] - 1 ) . '└─ ' : ''; // ┗
      }
      $title = $prefix . $row [$text];
      $d = '';
      foreach ( $dat as $p ) {
        $d .= sprintf ( ' data-%s="%s"', $p, $row [$p] );
      }
      $html .= sprintf ( '<option value="%s"%s>%s</option>', $value, $d, $title );
      
      if (isset ( $row ['son'] )) {
        $html .= form_options_rows ( $row ['son'], $id, $text, 0, $row ['level'] + 1 );
      }
    }
    
    if (! empty ( $selected_value )) {
      $html = str_replace ( 'value="' . $selected_value . '"', 'value="' . $selected_value . '" selected', $html );
    }
    
    return $html;
  }
}

if (! function_exists ( 'form_options_arr' )) {
  function form_options_arr($data) {
    $html = '';
    foreach ( $data as $val ) {
      $html .= '<option value="' . $val . '">' . $val . '</option>';
    }
    
    return $html;
  }
}

if (! function_exists ( 'form_radios' )) {
  function form_radios($name, $data, $checked_value = 0) {
    $html = '';
    foreach ( $data as $key => $val ) {
      $html .= '<label class="radio-inline"><input name="' . $name . '" type="radio" value="' . $key . '" >' . $val . '</label>';
    }
    
    if ($checked_value >= 0) {
      $html = str_replace ( 'value="' . $checked_value . '"', "value='$checked_value' checked", $html );
    }
    return $html;
  }
}

if (! function_exists ( 'form_checkbox' )) {
  function form_checkbox($name, $data, $checked_value = 0) {
    $html = '';
    foreach ( $data as $key => $val ) {
      $html .= '<label class="checkbox-inline"><input name="' . $name . '[]" type="checkbox" value="' . $key . '" >' . $val . '</label>';
    }
    
    if ($checked_value >= 0) {
      $html = str_replace ( 'value="' . $checked_value . '"', "value='$checked_value' checked", $html );
    }
    return $html;
  }
}

if (! function_exists ( 'form_checkbox_rows' )) {
  function form_checkbox_rows($name, $data, $id = 'id', $text = 'name', $checked_value = 0) {
    $html = '';
    foreach ( $data as $row ) {
      $html .= '<label class="checkbox-inline"><input name="' . $name . '" type="checkbox" value="' . $row [$id] . '" >' . $row [$text] . '</label>';
    }
    
    if ($checked_value >= 0) {
      $html = str_replace ( 'value="' . $checked_value . '"', "value='$checked_value' checked", $html );
    }
    return $html;
  }
}

if (! function_exists ( 'time_to' )) {
  function time_to($time_str) {
    $now = time ();
    $time = strtotime ( $time_str );
    $diff = $now - $time;
    
    if ($diff < 3600) {
      return floor ( $diff / 60 ) . '分钟前';
    } elseif ($diff < 86400) {
      return floor ( $diff / 3600 ) . '小时前';
    } elseif ($diff >= 86400 && $diff <= 259200) {
      return floor ( $diff / 86400 ) . '天前';
    } else {
      return date ( 'm月d日 H:i', strtotime ( $time_str ) );
    }
  }
}

if (! function_exists ( 'get_distance' )) {
  function get_distance($lat1, $lng1, $lat2, $lng2) {
    $earthRadius = 6367000; // approximate radius of earth in meters
    
    $lat1 = ($lat1 * pi ()) / 180;
    $lng1 = ($lng1 * pi ()) / 180;
    
    $lat2 = ($lat2 * pi ()) / 180;
    $lng2 = ($lng2 * pi ()) / 180;
    
    /*
     * Using the
     * Haversine formula
     *
     * http://en.wikipedia.org/wiki/Haversine_formula
     *
     * calculate the distance
     */
    
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow ( sin ( $calcLatitude / 2 ), 2 ) + cos ( $lat1 ) * cos ( $lat2 ) * pow ( sin ( $calcLongitude / 2 ), 2 );
    $stepTwo = 2 * asin ( min ( 1, sqrt ( $stepOne ) ) );
    $calculatedDistance = $earthRadius * $stepTwo;
    
    return round ( $calculatedDistance );
  }
}
function validation_filter_id_card($id_card) {
  if (strlen ( $id_card ) == 18) {
    return idcard_checksum18 ( $id_card );
  } elseif ((strlen ( $id_card ) == 15)) {
    $id_card = idcard_15to18 ( $id_card );
    return idcard_checksum18 ( $id_card );
  } else {
    return false;
  }
}

// 计算身份证校验码，根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base) {
  if (strlen ( $idcard_base ) != 17) {
    return false;
  }
  // 加权因子
  $factor = array (
      7,
      9,
      10,
      5,
      8,
      4,
      2,
      1,
      6,
      3,
      7,
      9,
      10,
      5,
      8,
      4,
      2 
  );
  // 校验码对应值
  $verify_number_list = array (
      '1',
      '0',
      'X',
      '9',
      '8',
      '7',
      '6',
      '5',
      '4',
      '3',
      '2' 
  );
  $checksum = 0;
  for($i = 0; $i < strlen ( $idcard_base ); $i ++) {
    $checksum += substr ( $idcard_base, $i, 1 ) * $factor [$i];
  }
  $mod = $checksum % 11;
  $verify_number = $verify_number_list [$mod];
  return $verify_number;
}

// 将15位身份证升级到18位
function idcard_15to18($idcard) {
  if (strlen ( $idcard ) != 15) {
    return false;
  } else {
    // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
    if (array_search ( substr ( $idcard, 12, 3 ), array (
        '996',
        '997',
        '998',
        '999' 
    ) ) !== false) {
      $idcard = substr ( $idcard, 0, 6 ) . '18' . substr ( $idcard, 6, 9 );
    } else {
      $idcard = substr ( $idcard, 0, 6 ) . '19' . substr ( $idcard, 6, 9 );
    }
  }
  $idcard = $idcard . idcard_verify_number ( $idcard );
  return $idcard;
}

// 18位身份证校验码有效性检查
function idcard_checksum18($idcard) {
  if (strlen ( $idcard ) != 18) {
    return false;
  }
  $idcard_base = substr ( $idcard, 0, 17 );
  if (idcard_verify_number ( $idcard_base ) != strtoupper ( substr ( $idcard, 17, 1 ) )) {
    return false;
  } else {
    return true;
  }
}
function del_dir_file($dirName) {
  if (file_exists ( $dirName )) {
    $handle = opendir ( "$dirName" );
    while ( false !== ($item = readdir ( $handle )) ) {
      if ($item != "." && $item != "..") {
        if (is_dir ( "$dirName/$item" )) {
          del_dir_file ( "$dirName/$item" );
        } else {
          unlink ( "$dirName/$item" );
        }
      }
    }
    closedir ( $handle );
    rmdir ( $dirName );
  }
}
function rand_string($length = 6) {
  $str = null;
  $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  $max = strlen ( $strPol ) - 1;
  
  for($i = 0; $i < $length; $i ++) {
    $str .= $strPol [rand ( 0, $max )]; // rand($min,$max)生成介于min和max两个数之间的一个随机整数
  }
  
  return $str;
}
function is_ajax_request() {
  if (isset ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) && strtolower ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest') {
    return true;
  } else {
    return false;
  }
}
